#include "pthread.hpp"
#include "Blockqueue.hpp"
#include "Task.hpp"
#include <time.h>

using namespace Thread;


using Blockqueue_t = Blockqueue<Task>;

void Productor(Blockqueue_t& bq)
{
    srand(time(nullptr));
    while (1)
    {
        sleep(1);
        //1.给任务
        int a = rand() % 10 + 1;
        usleep(1000);
        int b = rand() % 20 + 1;
        Task t(a,b);
        //2.通知消费者做任务
        bq.Enqueue(t);
        cout << "Productor->" << t.Add() << endl;
    }
}

void Consumer(Blockqueue_t& bq)
{
    while (1)
    {
        sleep(1);
        //1.取任务
        Task t;
        bq.Pop(&t);
        //2.做任务
        t.Excute();
        cout << "Consumer->" << t.Result() << endl;
    }
}


//创建线程 ————封装
void comm(vector<thread<Blockqueue_t>> *threads,int num,Blockqueue_t bq,func_t<Blockqueue_t> func)
{
    // 创建一批线程
    for (int i = 0; i < num; i++)
    {
        string name = "thread-" + to_string(i + 1);
        // thread<int> pro(ProductorCore,num,name);
        // threads->emplace_back(pro);
        threads->emplace_back(func, bq, name);
        // 启动线程
        threads->back().start();
    }
}
void StartProductor(vector<thread<Blockqueue_t>> *threads, int num,Blockqueue_t bq)
{
    comm(threads,num,bq,Productor);
}

void StartConsumer(vector<thread<Blockqueue_t>> *threads, int num,Blockqueue_t bq)
{
    comm(threads,num,bq,Consumer);
}

void WaitPhread(vector<thread<Blockqueue_t>>& threads)
{
    for (auto thread : threads)
    {
        thread.join();
    }
}

int main()
{
    Blockqueue_t* bq = new Blockqueue_t(5);
    vector<thread<Blockqueue_t>> threads;
    StartProductor(&threads, 1,*bq);
    StartConsumer(&threads, 1,*bq);
    WaitPhread(threads);
}